VPATH = stm32:stm32/start:src

RM = /usr/bin/rm
CC = /usr/bin/arm-none-eabi-gcc
GDB = /usr/bin/arm-none-eabi-gdb
OBJCOPY = /usr/bin/arm-none-eabi-objcopy
STFLASH = /usr/bin/st-flash
STUTIL  = /usr/bin/st-util

SECTIONS = stm32/start/sections.lds

FEATURE  = -mcpu=cortex-m3 -mthumb --specs=nano.specs
OPTIMIZE = -O3 -Werror -Wextra -Wno-pointer-to-int-cast
DEFINES  = -DSTM32F10X_MD -DUSE_STDPERIPH_DRIVER
INCLUDES = -I. -Isrc -Istm32 -Istm32/start

TARGETMAP = target.map

RMFLAGS = -r -v -f
STFLASHFLAGS = --format ihex
STFLASHADDR  = 
CFLAGS = $(FEATURE) $(OPTIMIZE) $(INCLUDES) $(DEFINES)
LDFLAGS = $(FEATURE) $(OPTIMIZE) -Wl,-Map,$(TARGETMAP) -nostartfiles -T $(SECTIONS)
OCPFLAGS = -g -S -R .comment -R .ARM.attributes -R .data.impure_data -R .data._impure_ptr

TARGET = target.hex
TARGET_BIN = target.bin
TARGET_OUT = target.out

STM32STARTUP = startup_stm32f10x_md.o
STM32CORE = core_cm3.o system_stm32f10x.o

# 需要监测更新的头文件
HEADERS = GProgressBar.h Object.h

# 添加 stm32 库
STM32UTILS = stm32f10x_gpio.o stm32f10x_rcc.o stm32f10x_adc.o \
	     stm32f10x_usart.o stm32f10x_tim.o misc.o stm32f10x_spi.o \
	     stm32f10x_i2c.o stm32f10x_exti.o

# 添加用户文件
SOURCES = main.o ADConvert.o AmperSensor.o Beep.o Network.o \
	  Serial.o Timer.o Tools.o VoltageSensor.o Error.o \
	  Screen.o Spi.o Leds.o GFonts.o GWidget.o GLabel.o \
	  GAlign.o GBox.o GProgressBar.o Object.o GWindow.o \
	  GText.o TempSensor.o PWMControl.o GScrolledWindow.o \
	  Application.o GDialog.o NfcCard.o Buttons.o VBattery.o

OBJECT = $(STM32CORE) $(STM32UTILS) $(SOURCES)

all: $(TARGET)

flash: $(TARGET)
	$(STFLASH) $(STFLASHFLAGS) write $^ $(STFLASHADDR)

erase:
	$(STFLASH) erase

debug: $(TARGET_OUT)
	$(GDB) $(TARGET_OUT)

$(TARGET): $(TARGET_OUT)
	$(OBJCOPY) $(OCPFLAGS) -O ihex $(TARGET_OUT) $@

$(TARGET_BIN): $(TARGET_OUT)
	$(OBJCOPY) $(OCPFLAGS) -O bin $(TARGET_OUT) $@

$(TARGET_OUT): $(STM32STARTUP) $(OBJECT)
	$(CC) $(LDFLAGS) -o $@ $^

$(STM32STARTUP): %.o : %.s
	$(CC) $(FEATURE) -c -o $@ $<

$(OBJECT): %.o : %.c $(HEADERS)
	$(CC) $(CFLAGS) -c -o $@ $<


.PHONY: clean
clean:
	$(RM) $(RMFLAGS) $(TARGET) $(TARGET_OUT) $(STM32STARTUP) $(OBJECT) $(TARGETMAP)
